const db=require('../db/index');

const bcrypt= require('bcryptjs');

const jwt=require('jsonwebtoken');

const config=require('../config');

exports.register=(req, res) => {
    const userinfo=req.body
    if(!userinfo.username || !userinfo.password){
        return res.send({status:1,message:'Username or password null'})
    }

    const sql='SELECT * FROM ev_users WHERE username=?';

    db.query(sql,[userinfo.username],(err,result)=>{
        if(err){
            //return res.send({status:1,message:err.message})
            return res.cc(err,3)
        }
        //用户被占用
        if(result.length>0){
            //return res.send({status:1,message:'user already exists'})
            return res.cc('username already exists,please change other username',1);
        }
        //对用户密码进行加密
        console.log('userinfo.password:' + userinfo.password);
        userinfo.password=bcrypt.hashSync(userinfo.password,10)
        console.log('userinfo.password:' + userinfo.password)

        //username is new ,insert a new user
        const sql ='insert into ev_users set ?'

        db.query(sql, {username:userinfo.username,password:userinfo.password},(err,result)=>{
            if(err){
                //return res.send({status:1,message:err.message})
                return res.cc(err)
            }
            if(result.affectedRows!==1){
                //return res.send({status:1,message:result.affectedRows})
                return res.cc('register user failed,please try again later',0);
            }
            //res.send({status:0,message:'register successfully'})
            res.cc('register successfully',0)
        })
    })
}

exports.login=(req, res) => {
    const userinfo=req.body;
    console.log(userinfo);
    const sql='SELECT * FROM ev_users WHERE username=?';
    db.query(sql,[userinfo.username],(err,result)=>{
        console.log(result.length)
        if(err) return res.cc(err,1);
        if(result.length!==1) return res.cc('login failed,please try again later',1);
        const compareResult = bcrypt.compareSync(userinfo.password, result[0].password);
        if(!compareResult){
            console.log('login failed');
            return res.cc('login failed,please try again later',1);
        }
        const user={...result[0],password:'',user_pic:''};
        const tokenStr=jwt.sign(user,config.jwtSecretKey,{expiresIn: '10h'});
        console.log(user);
        console.log('login successfully');
        res.send({
            status:0,
            message:'login successfully',
            token:'Bearer '+tokenStr,
        });
    })

}
